package individual.ircon.bilibili.ui;

import individual.ircon.bilibili.network.CommentHttpApi;
import javafx.application.Platform;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.control.*;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;

import static individual.ircon.bilibili.ui.Tools.showLotteryView;

public class CommentLottery implements Initializable {
    @FXML
    private Button LotteryBut;
    @FXML
    private Button ClearBut;
    @FXML
    private TableView<CommentItem> Table;
    @FXML
    private Label Title;
    @FXML
    private Label UpName;
    @FXML
    private Label VideoID;
    @FXML
    private TextField InputBv;
    @FXML
    private Button ActBut;
    private ObservableList<CommentItem> AllIt;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        AllIt = FXCollections.observableArrayList();

        /// TableView
        Table.setItems(AllIt);

        TableColumn<CommentItem, String> col_id = new TableColumn<>("用户ID");
        col_id.setCellValueFactory(param -> param.getValue().UserID.asString());

        TableColumn<CommentItem, String> col_name = new TableColumn<>("用户昵称");
        col_name.setCellValueFactory(param -> param.getValue().userNameProperty());

        TableColumn<CommentItem, String> col_com = new TableColumn<>("评论");
        col_com.setCellValueFactory(param -> param.getValue().commProperty());

        Table.getColumns().addAll(col_id, col_name, col_com);

    }

    /**
     * 获取加载器。拿到之后立刻load。
     *
     * @return 加载器。
     */
    public static FXMLLoader getLoader() {
        FXMLLoader loader = new FXMLLoader(CommentLottery.class.getResource("CommentLottery.fxml"));
        loader.setBuilderFactory(new JavaFXBuilderFactory());
        return loader;
    }

    private final Object SynTag = new Object();

    private void setDisable(boolean b) {
        ActBut.setDisable(b);
        LotteryBut.setDisable(b);
        ClearBut.setDisable(b);
        InputBv.setDisable(b);
    }
    @FXML
    private synchronized void buttonClick(ActionEvent actionEvent) {
        new Thread(() -> {
            synchronized (SynTag) {
                setDisable(true); // 防止在爬取过程中有操作。
                List<CommentHttpApi.Comment> lis = null;
                CommentHttpApi.VideoInfo info = null;
                try {
                    info = CommentHttpApi.getVideoInof(InputBv.getText());
                    if (info != null) {
                        lis = CommentHttpApi.getRootComment(info);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (lis == null) {
                    Alert al = new Alert(Alert.AlertType.ERROR);
                    al.setTitle("获取视频评论失败");
                    al.setContentText("请检查BV号是否正确，网络是否正常。");
                    al.show();
                } else {
                    CommentHttpApi.VideoInfo finalInfo = info; /// ??
                    Platform.runLater(()->{
                        Title.setText(finalInfo.Title);
                        UpName.setText(finalInfo.UpName);
                        VideoID.setText(Long.toString(finalInfo.Aid));
                    });

                    for (var v : lis) {
                        AllIt.add(new CommentItem(v.Mid, v.Name, v.Message));
                    }
                }
                setDisable(false);
            }
        }).start();

    }

    @FXML
    private void clearButtonClick(ActionEvent actionEvent) {
        synchronized (SynTag) {
            AllIt.clear();
        }

    }

    @FXML
    private void lotteryButtonClick(ActionEvent actionEvent) {
        synchronized (SynTag) {
            if(AllIt.isEmpty()) {
                Alert al = new Alert(Alert.AlertType.WARNING);
                al.setTitle("名单为空");
                al.setContentText("轻获取名单");
                al.show();
            }else{
                HashSet<Long> set = new HashSet<>();
                ArrayList<Shortlist> lis = new ArrayList<>();

                for(var v: AllIt) {
                    if(!set.contains(v.getUserID())) {
                        lis.add(new Shortlist(v.UserID, v.UserName));
                    }
                }
                showLotteryView(lis, 400, 400);
            }
        }
    }


    /**
     * 评论的数据。
     */
    public static class CommentItem {
        private final LongProperty UserID;
        private final StringProperty UserName;
        private final StringProperty Comm;

        public CommentItem(long id, String name, String comm) {
            UserID = new SimpleLongProperty(id);
            UserName = new SimpleStringProperty(name);
            Comm = new SimpleStringProperty(comm);
        }

        public CommentItem(LongProperty userID, StringProperty userName, StringProperty comm) {
            UserID = userID;
            UserName = userName;
            Comm = comm;
        }

        public long getUserID() {
            return UserID.get();
        }

        public LongProperty userIDProperty() {
            return UserID;
        }

        public void setUserID(long userID) {
            this.UserID.set(userID);
        }

        public String getUserName() {
            return UserName.get();
        }

        public StringProperty userNameProperty() {
            return UserName;
        }

        public void setUserName(String userName) {
            this.UserName.set(userName);
        }

        public String getComm() {
            return Comm.get();
        }

        public StringProperty commProperty() {
            return Comm;
        }

        public void setComm(String comm) {
            this.Comm.set(comm);
        }
    }
}
